package com.anywhere.freightman.common;

import com.anywhere.freightman.common.ex.CustomException;
import com.anywhere.freightman.common.request.PageRequest;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

public abstract class BaseController<T, QM> {

    public abstract IBaseEntityService<T, QM> getBaseService();

    @GetMapping("page")
    @ApiOperation("分页")
    public PageInfo<T> getPageList(QM qm) {
        PageRequest<QM> pageRequest = new PageRequest<>();
        BeanUtils.copyProperties(qm, pageRequest);
        pageRequest.setEntity(qm);
        return getBaseService().getPageList(pageRequest);
    }

    @GetMapping
    @ApiOperation("全部列表")
    public List<T> getAll() {
        return getBaseService().getAll();
    }

    @DeleteMapping
    @ApiOperation("删除")
    public void delete(@RequestParam("id") long id) {
        T model = getBaseService().getById(id);
        if (model != null) {
            getBaseService().delete(model);
        } else {
            //// TODO: 2018-12-30 统一抛出异常
        }
    }

    @GetMapping("{id}")
    @ApiOperation("详情")
    public T getDetails(@PathVariable("id") long id) {
        T model = getBaseService().getById(id);
        if (model == null) {
            throw new CustomException("信息不存在");
        }
        return model;
    }


}
